;
(function () {

  'use strict';

  angular.module('services.customActivity.summary')
    .service('summaryBusVolumeService', summaryBusVolumeService)
    .service('summaryFailVolumeService', summaryFailVolumeService)
    .service('summaryTotalRatioService', summaryTotalRatioService)
    .service('summaryBusVolumeContrastiveService', summaryBusVolumeContrastiveService)
    .service('summaryTopUpPreferService', summaryTopUpPreferService)
    .service('summaryBusLineRatioService', summaryBusLineRatioService)
    .service('summarySuccessVolumeService', summarySuccessVolumeService);

  function summaryBusLineRatioService(Restangular, generatorSummaryPageService) {
    var that = this;
    var option = {
      tooltip: {
        trigger: 'item',
        formatter: "{b}: {d}%"
      },
      series: [
        {
          type: 'pie',
          radius: '48%',
          center: ['50%', '58%'],
          data: []
        }
      ]
    };
    this.init = function (element) {

      if (generatorSummaryPageService.pageInfo.preview) {
        setTimeout(function () {
          option.series[0].data = [];
          that.loading = true;
          option.series[0].data = [
            {value: 1, name: '天猫旗舰店'},
            {value: 1, name: '移动商城'},
            {value: 1, name: '银行总对总'},
            {value: 1, name: '有价卡'},
            {value: 1, name: '灵犀语音'}
          ];
          (echarts.init(element)).setOption(option);
        }, 0);
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/busLineRatio/query').post({
        summaryId: generatorSummaryPageService.pageInfo.summaryId
      }).then(function (result) {
        that.loading = true;
        option.series[0].data = [];
        if (result.state === '10000') {
          angular.forEach(result.data, function (value, key) {
            option.series[0].data.push({
              value: value,
              name: getTitleBySys(key.toUpperCase())
            });
          });
        }
        (echarts.init(element)).setOption(option);
      });
    };
  }

  summaryBusLineRatioService.$inject = ['Restangular', 'generatorSummaryPageService'];

  function summaryBusVolumeService(Restangular, generatorSummaryPageService, SUMMARY_MODULE) {

    this.loading = true;
    var that = this;

    this.init = function () {
      that.UPAYS = false;
      that.TMALLS = false;
      that.SCPAYS = false;
      that.BANKS = false;
      that.VCES = false;
      that.LINGXI = false;
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.UPAY) >= 0 && queryBySys('UPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.TMALL) >= 0 && queryBySys('TMALL');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.SCPAY) >= 0 && queryBySys('SCPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.BANK) >= 0 && queryBySys('BANK');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.VCES) >= 0 && queryBySys('VCES');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.BUS_VOLUME.LINGXI) >= 0 && queryBySys('LINGXI');
    };

    function queryBySys(sys) {

      that[sys + 'S'] = true;

      if (generatorSummaryPageService.pageInfo.preview) {
        that.loading = true;
        that[sys] = 0;
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/busVolume/query').post({
        activityId: generatorSummaryPageService.pageInfo.activityId
      }).then(function (result) {
        that.loading = true;
        if (result.state === '10000') {
          that[sys] = result.data[sys.toLowerCase()];
        } else {
          that[sys] = 0;
        }
      });
    };
  }

  summaryBusVolumeService.$inject = ['Restangular', 'generatorSummaryPageService', 'SUMMARY_MODULE'];

  function summarySuccessVolumeService(Restangular, generatorSummaryPageService, SUMMARY_MODULE) {

    this.loading = true;
    var that = this;

    this.init = function () {
      that.UPAYS = false;
      that.TMALLS = false;
      that.SCPAYS = false;
      that.BANKS = false;
      that.VCES = false;
      that.LINGXI = false;
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.UPAY) >= 0 && queryBySys('UPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.TMALL) >= 0 && queryBySys('TMALL');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.SCPAY) >= 0 && queryBySys('SCPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.BANK) >= 0 && queryBySys('BANK');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.VCES) >= 0 && queryBySys('VCES');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.SUCCESS_VOLUME.LINGXI) >= 0 && queryBySys('LINGXI');
    };

    function queryBySys(sys) {

      that[sys + 'S'] = true;

      if (generatorSummaryPageService.pageInfo.preview) {
        that.loading = true;
        that[sys] = 0;
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/successVolume/query').post({
        activityId: generatorSummaryPageService.pageInfo.activityId
      }).then(function (result) {
        that.loading = true;
        if (result.state === '10000') {
          that[sys] = result.data[sys.toLowerCase()];
        } else {
          that[sys] = 0;
        }
      });
    };
  }

  summarySuccessVolumeService.$inject = ['Restangular', 'generatorSummaryPageService', 'SUMMARY_MODULE'];

  function summaryFailVolumeService(Restangular, generatorSummaryPageService, SUMMARY_MODULE) {

    var that = this;
    this.loading = true;

    this.init = function () {
      that.UPAYS = false;
      that.TMALLS = false;
      that.SCPAYS = false;
      that.BANKS = false;
      that.VCES = false;
      that.LINGXI = false;
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.UPAY) >= 0 && queryBySys('UPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.TMALL) >= 0 && queryBySys('TMALL');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.SCPAY) >= 0 && queryBySys('SCPAY');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.BANK) >= 0 && queryBySys('BANK');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.VCES) >= 0 && queryBySys('VCES');
      generatorSummaryPageService.pageInfo.selectedModules.indexOf(SUMMARY_MODULE.FAIL_VOLUME.LINGXI) >= 0 && queryBySys('LINGXI');
    };

    function queryBySys(sys) {

      that[sys + 'S'] = true;

      if (generatorSummaryPageService.pageInfo.preview) {
        that.loading = true;
        that[sys] = 0;
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/failVolume/query').post({
        activityId: generatorSummaryPageService.pageInfo.activityId
      }).then(function (result) {
        that.loading = true;
        if (result.state === '10000') {
          that[sys] = result.data[sys.toLowerCase()];
        } else {
          that[sys] = 0;
        }
      });
    };
  }

  summaryFailVolumeService.$inject = ['Restangular', 'generatorSummaryPageService', 'SUMMARY_MODULE'];

  function summaryTotalRatioService(Restangular, generatorSummaryPageService, COREDATA) {

    var that = this;

    var option = {
      tooltip: {
        trigger: 'item',
        formatter: "{b}: {d}%"
      },
      series: [
        {
          type: 'pie',
          radius: '78%',
          center: ['50%', '58%'],
          data: []
        }
      ]
    };

    this.queryBySys = function (sys, element) {
      if (generatorSummaryPageService.pageInfo.preview) {
        setTimeout(function () {
          that.loading = true;
          option.series[0].data = [];
          angular.forEach(generatorSummaryPageService.pageInfo.provinceCodes, function (code, index) {
            angular.forEach(COREDATA.PROVINCES, function (province) {
              if (code === province.provinceCode) {
                var show = true;
                if (index > 7) {
                  show = false;
                }
                option.series[0].data.push({
                  name: province.provinceName,
                  value: 1,
                  itemStyle: {
                    normal: {
                      label: {show: show},
                      labelLine: {show: show, length: 15}
                    }
                  }
                });
              }
            });
          });
          (echarts.init(element[0])).setOption(option);
        }, 0);
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/totalRatio/query').post({
        activityId: generatorSummaryPageService.pageInfo.activityId
      }).then(function (result) {
        that.loading = true;
        option.series[0].data = [];
        if (result.state === '10000') {
          var total = 0;
          angular.forEach(result.data[sys.toLowerCase()], function (obj) {
            total += obj.busVolume;
          });
          angular.forEach(result.data[sys.toLowerCase()], function (obj) {
            option.series[0].data.push({
              name: obj.provinceName,
              value: (obj.busVolume / total) || 1,
              itemStyle: {
                normal: {
                  label: {show: false},
                  labelLine: {show: false, length: 15}
                }
              }
            });
          });
          option.series[0].data.sort(function (a, b) {
            if (a.value > b.value) {
              return -1;
            }
            if (a.value === b.value) {
              return 0;
            }
            else {
              return 1;
            }
          });
        }
        for (var i = 0; i < 8 && i < option.series[0].data.length; i++) {
          option.series[0].data[i].itemStyle.normal.label = {show: true};
          option.series[0].data[i].itemStyle.normal.labelLine = {show: true, length: 15};
        }
        (echarts.init(element[0])).setOption(option);
      });
    }
  }

  summaryTotalRatioService.$inject = ['Restangular', 'generatorSummaryPageService', 'COREDATA'];

  function summaryBusVolumeContrastiveService(Restangular, generatorSummaryPageService) {

    this.list = {};
    var that = this;
    var option = {
      title: {
        text: '',
        x: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (dataList) {
          return '<div style=\'text-align: left;\'>日期: ' + dataList[0].name + '<br/>' +
            dataList[0].seriesName + ': ' + dataList[0].value + '（笔）<br/>' +
            dataList[1].seriesName + ': ' + dataList[1].value + '（笔）<br/>' +
            dataList[2].seriesName + ': ' + (parseFloat(dataList[2].value)).toFixed(2) + '%</div>';
        }
      },
      legend: {
        data: []
      },
      toolbox: {},
      xAxis: [
        {
          type: 'category',
          data: []
        }
      ],
      yAxis: [
        {
          type: 'value',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        {
          type: 'value',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '今年业务量',
          type: 'bar',
          data: []
        },
        {
          name: '去年业务量',
          type: 'bar',
          data: []
        },
        {
          name: '同比增长率',
          type: 'line',
          data: [],
          yAxisIndex: 1
        }
      ],
      grid: {borderWidth: 0, y: '32%', x: '10%', x2: '10%', y2: '18%'}
    };


    this.init = function (sys, element) {

      if (generatorSummaryPageService.pageInfo.preview) {
        setTimeout(function () {
          that.loading = true;
          that.list[sys] = [];
          option.title.text = getTitleBySys(sys);
          option.xAxis[0].data = [];
          option.series[0].data = [];
          option.series[1].data = [];
          option.series[2].data = [];
          var startTime = (new Date(generatorSummaryPageService.pageInfo.startTime)).getTime();
          var endTime = (new Date(generatorSummaryPageService.pageInfo.endTime)).getTime();
          for (var i = startTime; i <= endTime; i += 86400000) {
            var time = new Date(i);
            var year = time.getFullYear();
            var month = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1);
            var day = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
            that.list[sys].push({
              date: year + '-' + month + '-' + day,
              thisYearBusVolume: 0,
              lastYearBusVolume: 0,
              growthRate: 0.00
            });
            option.xAxis[0].data.push(year + '-' + month + '-' + day);
            option.series[0].data.push(0);
            option.series[1].data.push(0);
            option.series[2].data.push(0.00);
          }
          (echarts.init(element[0])).setOption(option);
        }, 0);
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/busVolumeContrastive/query').post({
        summaryId: generatorSummaryPageService.pageInfo.summaryId
      }).then(function (result) {
        that.loading = true;
        if (result.state === '10000') {
          that.list[sys] = result.data[sys.toLowerCase()];
          option.title.text = getTitleBySys(sys);
          option.xAxis[0].data = [];
          option.series[0].data = [];
          option.series[1].data = [];
          option.series[2].data = [];
          angular.forEach(that.list[sys], function (obj) {
            option.xAxis[0].data.push(obj.date);
            option.series[0].data.push(obj.thisYearBusVolume);
            option.series[1].data.push(obj.lastYearBusVolume);
            option.series[2].data.push(obj.growthRate);
          });
          (echarts.init(element[0])).setOption(option);
        }
      });
    };
  }

  summaryBusVolumeContrastiveService.$inject = ['Restangular', 'generatorSummaryPageService', 'SUMMARY_MODULE'];

  function getTitleBySys(sys) {
    switch (sys) {
      case 'UPAY':
        return '统一支付';
      case 'TMALL':
        return '天猫旗舰店';
      case 'SCPAY':
        return '移动商城';
      case 'BANK':
        return '银行总对总';
      case 'VCES':
        return '有价卡';
      case 'LINGXI':
        return '灵犀语音';
    }
  }

  function summaryTopUpPreferService(Restangular, generatorSummaryPageService) {
    var that = this;
    var option = {
      title: {text: '', x: 'center', textStyle: {fontSize: 14}, padding: 0},
      tooltip: {
        trigger: 'item',
        formatter: '订单金额（元）: {b}<br/>交易量（万笔）: {c}'
      },
      legend: {
        show: false,
        data: []
      },
      grid: {borderWidth: 0, y: '12%', x: '12%', x2: '12%'},
      toolbox: {
        show: false
      },
      xAxis: [
        {
          type: 'value',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        }
      ],
      yAxis: [
        {
          name: '充值金额(元)',
          type: 'category',
          data: [],
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {show: true, interval: 0, textStyle: {baseline: "middle"}}
        }
      ],
      series: [
        {
          clickable: false,
          type: 'bar',
          data: []
        }
      ]
    };

    this.queryBySys = function (sys, element) {

      if (generatorSummaryPageService.pageInfo.preview) {
        setTimeout(function () {
          that.loading = true;
          option.title.text = getTitleBySys(sys);
          option.yAxis[0].data = ["(0,5]", "(5,20]", "(20,50]", "(50,100]", "(100,150]", "(150,200]", "(200,+]"];
          option.series[0].data = [0, 0, 0, 0, 0, 0, 0];
          (echarts.init(element[0])).setOption(option);
        }, 0);
        return;
      }

      that.loading = false;
      Restangular.all('sas/customActivity/summary/busVolume/userRechargePreference/query').post({
        summaryId: generatorSummaryPageService.pageInfo.summaryId
      }).then(function (result) {
        that.loading = true;
        if (result.state === '10000') {
          result = result.data[sys.toLowerCase()];
          if (result.unit === 1) {
            that[sys] = '万笔';
            option.tooltip.formatter = '订单金额（元）: {b}<br/>交易量（万笔）: {c}';
          } else {
            that[sys] = '笔';
            option.tooltip.formatter = '订单金额（元）: {b}<br/>交易量（笔）: {c}';
          }
          option.title.text = getTitleBySys(sys);
          option.yAxis[0].data = result.rechargeAmount;
          option.series[0].data = result.volumeOfTrans;
          var chart = echarts.init(element[0]);
          chart.setOption(option);
        }
      });
    };
  }

  summaryTopUpPreferService.$inject = ['Restangular', 'generatorSummaryPageService', 'SUMMARY_MODULE'];
})();